package cn.ichiva.puppet.example.postwoman;

import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.FXMLPath;
import javafx.fxml.impl.AbstractPuppetComponent;
import javafx.scene.control.*;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;

@FXMLPath("postwoman-view.fxml")
public class PostWomanView extends AbstractPuppetComponent {
    private static final  org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(WSServer.class);

    @FXML
    StringProperty url = new SimpleStringProperty("ws://127.0.0.1:11219");

    @FXML
    StringProperty receiveMessage = new SimpleStringProperty("");

    @FXML
    void receiveMessageClean(){
        receiveMessage.set("");
    }

    @FXML
    StringProperty sendMessage = new SimpleStringProperty("");

    @FXML
    StringProperty notice = new SimpleStringProperty(""){
        {
            addListener((observableValue, old, newText) -> {
                if(newText != null && newText.length() != 0){
                    //延迟清除
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask(){
                            public void run(){
                                cleanNotice();
                                timer.cancel();
                            }
                        },3000);

                }
            });
        }
    };

    void cleanNotice(){
       Platform.runLater(() ->  notice.set(""));
    }

    @FXML
    void send(){
        String text = sendMessage.get();
        if(null == text || text.length() == 0){
            notice.set("消息为空.");
            return;
        }

        if(client == null){
            notice.set("未连接到服务器.");
            return;
        }

        client.send(text);
    }

    @FXML
    void format(){
        sendMessage.set("格式未实现");
    }

    @FXML
    public WebSocketClient client = null;

    @FXML
    void conn(){
        connClose();
        WebSocketClient client;
        try {
            client = new WebSocketClient(new URI(url.get())){

                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    receiveMessage.set(String.format("""
                            [%s] 连接到服务器
                            
                            %s
                            """,new Date(),receiveMessage.get()));
                }

                @Override
                public void onMessage(String s) {
                    receiveMessage.set(String.format("""
                            [%s] 收到
                            %s
                            
                            %s
                            """,new Date(),s,receiveMessage.get()));
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    receiveMessage.set(String.format("""
                            [%s] 关闭连接
                            
                            %s
                            """,new Date(),receiveMessage.get()));
                }

                @Override
                public void onError(Exception e) {
                    receiveMessage.set(String.format("""
                            [%s] 发生错误
                            %s
                            
                            %s
                            """,new Date(),e.getMessage(),receiveMessage.get()));
                }
            };
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }

        client.connect();
        this.client = client;
        update();
    }

    @FXML
    void connClose(){
        if (client != null) {
            try {
                client.close();
            }catch (Exception e){
                log.error("关闭ws出错",e);
            }
            client = null;
        }
        update();
    }

    @FXML
    StringProperty favoriteName = new SimpleStringProperty();

    //消息收藏夹
    @FXML
    public Map<String,String> favorites = new HashMap<>(){
        {
            put("5点钟方向出击","向150度方向开火");
            put("9点钟方向出击","向270度方向开火");
        }
    };

    @FXML
    void favorite(){
        String key = favoriteName.get();
        String value = sendMessage.get();
        if(key != null && value != null && value.length() != 0 && key.length() != 0){
            favorites.put(key,value);
            update();
        }
    }

    @FXML
    void removeFavorite(Event event){
        Button button = (Button) event.getSource();
        String key = button.getUserData().toString();
        favorites.remove(key);
        update();
    }

    @FXML
    void selectFavorite(Event event){
        Button button = (Button) event.getSource();
        String key = button.getUserData().toString();
        String value = favorites.get(key);

        sendMessage.set(value);
    }



    boolean historyFlag = false;

    @FXML
    void historyToggle(){
        historyFlag = !historyFlag;
        update();
    }

    List<String> historyList = new ArrayList<>(Arrays.asList("A","B","C","D"));

    @FXML
    void removeHistory(Event event){
        Button button = (Button) event.getSource();
        int index = Integer.parseInt(button.getUserData().toString());
        historyList.remove(index);
        update();
    }


}
